package com.ayf.payment.game.api.filter;

import com.ayf.payment.game.api.auths.AbstractAuthorization;
import com.ayf.payment.game.api.auths.OAuthAuthorization;
import com.ayf.payment.game.api.bean.AuthorizationInfo;
import com.ayf.payment.game.api.bean.WrapperHttpServletRequest;
import com.ayf.payment.game.api.dto.platform.AdminUserDTO;
import com.ayf.payment.game.api.dto.platform.TokenAdmin;
import com.ayf.payment.game.api.entity.platform.AdminUser;
import com.ayf.payment.game.api.exception.AuthorizeFailedException;
import com.ayf.payment.game.api.service.platform.AdminUserService;
import com.ayf.payment.game.api.service.platform.TokenAdminRepository;
import com.ayf.payment.game.api.type.AuthorizationType;
import com.ayf.payment.game.api.utils.IPUtils;
import com.ayf.payment.game.api.utils.MapUtil;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 *
 * @author wwl
 * @date 2020/3/4 17:00
 */
@WebFilter(urlPatterns = "/t/*", filterName = "authorPlatformFilter")
public class AuthorizationPlatformFilter extends BasicPlatforFilter implements Filter  {

        @Autowired
        private TokenAdminRepository tokenAdminRepository;

        @Autowired
        private AdminUserService adminUserService;
        @Resource
        private OAuthAuthorization oAuthAuthorization;
       @Resource
       private AbstractAuthorization abstractAuthorization;

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

    }

        /**
         * 处理授权
         * @param request
         * @param response
         * @param chain
         * @throws IOException
         * @throws ServletException
         */
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        String ip = IPUtils.getIp(req);
        HttpServletResponse res = (HttpServletResponse)response;
        WrapperHttpServletRequest reqWrapper = new WrapperHttpServletRequest(req);
//        LogPortal.info("{} url:[{}] ",this.getClass().getName(),req.getRequestURI());
        //需要校验的请求
        if (!isContain(req.getRequestURI(), canAlwaysVisits)) {
            try {
                //获取实例
                AbstractAuthorization authorization = abstractAuthorization.getInstanceByAuthType(req);
                //签名校验
                AuthorizationInfo authorizationInfo = authorization.execute(reqWrapper);
                reqWrapper.setPrincipal(authorizationInfo);
            } catch (Exception e) {
                handleException(res, e);
                return;
            }
        }

        AuthorizationInfo authorizationInfo = (AuthorizationInfo) reqWrapper.getUserPrincipal();
        if (authorizationInfo != null) {
            //设置Customer信息
            AdminUserDTO adminUserDTO = null;
            try {
                if (authorizationInfo.getAuthType() == AuthorizationType.OAUTH) {//需要校验Token
                    if (StringUtils.isBlank(authorizationInfo.getAuthValue())) {
                        throw new AuthorizeFailedException("accessToken cannot be null");
                    }
                    TokenAdmin tokenAdmin = tokenAdminRepository.getTokenByAccessToken(authorizationInfo.getAuthValue());
                    if (null == tokenAdmin || !tokenAdmin.getIp().equals(ip)) {
                        throw new AuthorizeFailedException("Authorization failed, please login again");

                    } else {
                        AdminUser temp = new AdminUser();
                        temp.setId(tokenAdmin.getAdminUserId());
                        adminUserDTO = adminUserService.selectOneDTO(temp);
                        if (adminUserDTO == null) {
                            throw new AuthorizeFailedException("Authorization failed, please login again");
                        }
                    }
                }
            } catch (AuthorizeFailedException e) {
                handleException(res, e);
                return;
            }
            reqWrapper.setPrincipal(adminUserDTO);
        }
        chain.doFilter(reqWrapper, res);
    }

        @Override
        public void destroy() {

    }
}
